﻿$.fn.showFilter = function () {
    var mouse_is_inside = true;

    this.click(function () {
        mouse_is_inside = true;
        
        var curr_el = $(this);
        var wrapper = curr_el.parent().parent();
        var link = curr_el.parent();

        if (wrapper.hasClass('active')) {
            wrapper.removeClass('active');
        } else {
            $('.filter-wrapper.active').removeClass('active');
            Falkor.initShowModal($(this));
            wrapper.addClass('active');
        }

        $(wrapper, link).hover(function () {
            mouse_is_inside = true;
        }, function () {
            mouse_is_inside = false;
        });

        var divDatePicker = $('#ui-datepicker-div');

        $(divDatePicker).hover(function () {
            mouse_is_inside = true;
        }, function () {
            mouse_is_inside = false;
        });

        return false;
    });

    $(document).click(function () {
        if (!mouse_is_inside) {
            $('.filter-wrapper.active').removeClass('active');
        }
    });
};

var _SEARCH_DELAY_MS = 175; 				//Prevents unnecessary async requests
var _SEARCH_INTERVAL_MS = 750; 				//Time between building Search Results (for IE slowness)
var _DATE_FORMAT = 'mm/dd/yy';

var _searchItemsDelayTimeoutHandler = null;
var _compiledTemplate_SearchResults = "";
var _compiledTemplate_SelectedItems = "";

var StringUtil = L360.StringUtil;


$(document).ready(function () {
    // Filters init
    $('.filter-trigger').showFilter();

    $('.leadfilter-search a').click(Falkor.itemClicked);

    $('.leadfilter-done').click(Falkor.applySelectedItems);

    $('.rangeSelectItem').click(Falkor.applyRangeTime);

    $('.leadfilter-range-done').click(Falkor.applyDateTimePicker);

    $('.leadFilter-cancel').click(function () { $('.filter-wrapper.active').removeClass('active'); });

    $('.leadFilter-search').keyup(Falkor.searchItemsDelay);

    //---Compile doT Templates---
    //Note: Compiling once is best for performance!
    _compiledTemplate_SelectedItems = doT.compile(Falkor.Templates.dotSelectedItems);
});


//Using Object Literal Notation Namespacing
var Falkor = {

    //===doT Templates============================================================
    Templates:
	{
	    //Improper Html: Duplicate Id; Remove Id from the anchor.
	    dotSelectedItems:
		' \
			<li id="{{=it.itemId}}" itemtitle="{{=it.itemTitle}}" style="{{=it.itemLength<=16?\"margin-right:60px\":\""}}"> \
				{{=it.itemTitle}} <a href="javascript:void(0)" class="btn btn-x">Delete</a>\
			</li> \
		'
	},

    initShowModal: function (object) {
        var inputSelector = object.parent().children('input');
        var filterType = inputSelector.attr('filtertype');
        var type = '';
        var allTitle = '';
        var dataSource;

        // switch filter type
        switch (filterType) {
            case 'status':
                type = 's'; allTitle = 'Tất cả'; dataSource = data.StatusFilter; break;
            case 'user':
                type = 'u'; allTitle = 'Tất cả'; dataSource = data.UserFilter; break;
            case 'leadsource':
                type = 'l'; allTitle = 'Tất cả'; dataSource = data.LeadSource; break;
            case 'range':
                break;
        }

        if (filterType != 'range') {
            // hanle multi select

            var searchItemListUL = $('.leadfilter-search[filtertype=' + filterType + ']');
            var selectedItemListUL = $('.leadfilter-selected[filtertype=' + filterType + ']');
            var selectedItem = {};

            // Reset search UL and selected UL
            htmlSelectedItem = '';
            searchItemListUL.children('li').removeClass('div-hide');

            // reset search text
            searchItemListUL.parent().children('input').val('');
            searchItemListUL.children('li').removeClass('hideItemSearch');

            var selectedValue = inputSelector.val();

            if (selectedValue != undefined && selectedValue != null && selectedValue != '') {
                var selectedValueArray = selectedValue.split(',');

                for (var i = 0; i < selectedValueArray.length; i++) {
                    selectedItem['id'] = selectedValueArray[i] + type;

                    for (var j = 0; j < dataSource.length; j++) {
                        if (dataSource[j].ID == selectedValueArray[i]) {
                            selectedItem['title'] = dataSource[j].ItemName;
                            break;
                        }
                    }

                    htmlSelectedItem += Falkor.buildSelectedItemHtml(selectedItem['id'], selectedItem['title']);

                    // hide item on search list
                    Falkor.hideSearchResultItem(selectedItem['id']);
                }
            }
            else {
                Falkor.hideSearchResultItem('-10' + type);
                htmlSelectedItem = Falkor.buildSelectedItemHtml('-10' + type, allTitle);
            }

            //---Update UI---
            selectedItemListUL.html(htmlSelectedItem);

            //---WireUp A tag (Yes, reselect)---
            var selectItemUL_A = $('.leadfilter-selected[filtertype=' + filterType + '] a');
            $(selectItemUL_A).click(Falkor.itemSelectedClicked);
        }
        else {
            // hanle range time

            // reset picker
            $("#startDate").val('');
            $("#endDate").val('');

            // hanle
            if (inputSelector.attr('timepicker') == 'true') {
                var selectedTime = inputSelector.val();
                var array = selectedTime.split('|');
                $("#startDate").val(array[0]);
                if (GetCurrentDate() == array[1]) {
                    $("#endDate").val('');
                }
                else {
                    $("#endDate").val(array[1]);
                }
            }
        }

    },

    applySelectedItems: function () {
        var filterType = $(this).parent().parent().children('ul').attr('filtertype');

        var hiddenSelector;
        var textTitle = '';
        switch (filterType) {
            case 'status':
                hiddenSelector = '#StatusSelectedValue'; textTitle = 'Tình trạng'; break;
            case 'user':
                hiddenSelector = '#UserSelectedValue'; textTitle = 'Người dùng'; break;
            case 'leadsource':
                hiddenSelector = '#LeadSourceSelectedValue'; textTitle = 'Nguồn khách hàng'; break;
        }

        if (hiddenSelector != undefined && hiddenSelector != null) {
            var selectedItemsLI = $(this).parent().parent().children('ul').children('li');

            if (selectedItemsLI.length > 0) {
                var valueSelected = '';

                if (selectedItemsLI[0].id.substr(0, selectedItemsLI[0].id.length - 1) != '-10') {

                    for (var i = 0; i < selectedItemsLI.length; i++) {
                        valueSelected += selectedItemsLI[i].id.substr(0, selectedItemsLI[i].id.length - 1) + ',';
                    }

                    // Remove a last comas
                    if (valueSelected.length > 0) {
                        valueSelected = valueSelected.substr(0, valueSelected.length - 1);
                    }
                }

                // Set selected value
                $(hiddenSelector).val(valueSelected);

                // set title for list
                if (selectedItemsLI.length > 1) {
                    $('.leadFilter-title[filtertype="' + filterType + '"]').text(selectedItemsLI.length + ' ' + textTitle);
                }
                else {
                    $('.leadFilter-title[filtertype="' + filterType + '"]').text(selectedItemsLI.attr('itemtitle'));
                }

                // close modal window
                $('.filter-wrapper.active').removeClass('active');
            }
        }
    },

    itemClicked: function () {
        // Get current
        var itemId = $(this).attr('id');
        var itemTitle = $(this).attr('itemtitle');
        var filterType = $(this).parent().parent().attr('filtertype');

        var selectItemUL = $('.leadfilter-selected[filtertype=' + filterType + ']');
        var selectItemUL_LI = selectItemUL.children('li');
        var htmlSelectedItem = '';

        // check for selected item is all ~ (-10)
        if (selectItemUL_LI != undefined && selectItemUL_LI != null && selectItemUL_LI.length > 0) {

            var selectItemUL_LIid = selectItemUL_LI.attr('id');
            var selectItemUL_LIid2 = selectItemUL_LIid.substr(0, selectItemUL_LIid.length - 1);

            if (selectItemUL_LIid2 == '-10') {
                Falkor.unhideSearchResultItem(selectItemUL_LIid);
            }
            else {
                htmlSelectedItem = selectItemUL.html();
            }
        }

        //---Append---
        itemIdTemp = itemId.substr(0, itemId.length - 1);
        if (itemIdTemp == '-10') {
            htmlSelectedItem = Falkor.buildSelectedItemHtml(itemId, itemTitle);

            // Unhide all element of selected list
            for (var i = 0; i < selectItemUL_LI.length; i++) {
                Falkor.unhideSearchResultItem(selectItemUL_LI[i].id);
            }
        }
        else {
            htmlSelectedItem += Falkor.buildSelectedItemHtml(itemId, itemTitle);
        }

        //---Update UI---
        selectItemUL.html(htmlSelectedItem);

        //---WireUp A tag (Yes, reselect)---
        var selectItemUL_A = $('.leadfilter-selected[filtertype=' + filterType + '] a');
        $(selectItemUL_A).click(Falkor.itemSelectedClicked);

        //---Hide Li from DOM---
        Falkor.hideSearchResultItem(itemId);

    },

    itemSelectedClicked: function () {
        var itemId = $(this).parent().attr('id');
        var itemTitle = $(this).parent().attr('itemtitle');
        var filterType = $(this).parent().parent().attr('filtertype');

        //---Remove from SelectedUL---
        $('.leadfilter-selected[filtertype="' + filterType + '"]').children('#' + itemId).remove();

        //---Show Back in Search List---
        Falkor.unhideSearchResultItem(itemId);
    },

    buildSelectedItemHtml: function (itemId, itemTitle) {
        //---Build object to hold info---
        var selectedItem = {};
        selectedItem["itemId"] = itemId;
        selectedItem["itemTitle"] = StringUtil.htmlEncode(itemTitle);
        selectedItem["itemLength"] = itemTitle.length;

        //---Apply and Return Template---
        return _compiledTemplate_SelectedItems(selectedItem);
    },

    hideSearchResultItem: function (id) {
        var searchResultItem = $('li#' + id);
        searchResultItem.addClass('div-hide');
    },

    unhideSearchResultItem: function (id) {
        //NOTE: http: //jsperf.com/jquery-selection-on-falkor-search-results
        //WARNING: Utilizing the Html Id attribute is great for performance, but since
        // the Id value is the id directly, conflicts may occur in the future. -mjew

        var searchResultItem = $('li#' + id);
        searchResultItem.removeClass('div-hide');
    },

    applyRangeTime: function () {
        var valueSelected = $(this).attr('id');
        if (valueSelected != '-1') {
            $('#RangeSelectedValue').val(valueSelected);

        }
        else {
            $('#RangeSelectedValue').val('');
        }
        $('#RangeSelectedValue').attr('timepicker', 'false');
        $('.leadFilter-range-title').text($(this).text());

        $('.filter-wrapper.active').removeClass('active');
    },

    applyDateTimePicker: function () {
        var startDate = $('#startDate').val();
        var endDate = $('#endDate').val();
        $('.filter-wrapper.active').removeClass('active');

        if (startDate != null && startDate != '') {
            var dateTitle = '';
            if (startDate == endDate) {
                dateTitle = startDate;
            }
            else if (endDate == null || endDate == '' || endDate == undefined) {
                dateTitle = 'From ' + startDate;
            }
            else {
                dateTitle = startDate + ' - ' + endDate;
            }
            $('.leadFilter-range-title').text(dateTitle);

            if (endDate == undefined || endDate == null || endDate == '') {
                endDate = GetCurrentDate();
            }

            $('#RangeSelectedValue').val(startDate + '|' + endDate);
            $('#RangeSelectedValue').attr('timepicker', 'true');
        }
    },

    searchItemsDelay: function () {
        try {
            clearTimeout(_searchItemsDelayTimeoutHandler);
            _searchItemsDelayTimeoutHandler = setTimeout(Falkor.searchItems($(this)), _SEARCH_DELAY_MS);
        }
        catch (err) {
            //Handle errors here
        }
    },

    searchItems: function (object) {
        var inputValue = object.val();
        var searchItemListUL = object.parent().children('ul');
        var searchItemListUL_LI = searchItemListUL.children('li');
        var filterType = searchItemListUL.attr('filtertype');

        searchItemListUL_LI.each(function () {
            var sText = $(this).children('a').attr('itemtitle');
            if (sText.toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
                $(this).removeClass('hideItemSearch');
            }
            else {
                $(this).addClass('hideItemSearch');
            }
        });
    }
}
//end namespace

function GetCurrentDate() {
    var currentDate = new Date();
    var dd = currentDate.getDate();
    var mm = currentDate.getMonth() + 1;
    var yyyy = currentDate.getFullYear();
    if (dd < 10) { dd = '0' + dd; }
    if (mm < 10) { mm = '0' + mm; }
    return (mm + '/' + dd + '/' + yyyy);
}

// Fire event when datetime inputbox lost focus
// Set CurrentDatetime for it
function formatDate(object) {
    var dateStr = object.val();

    try {
        var date = $.datepicker.parseDate(_DATE_FORMAT, dateStr);
        var formattedDateStr = $.datepicker.formatDate(_DATE_FORMAT, date);

        object.val(formattedDateStr);
    }
    catch (err) {
        var formattedDateStr = $.datepicker.formatDate(_DATE_FORMAT, new Date()); //Current Date
        object.val(formattedDateStr);
    }
}

$('#startDate').blur(function () {
    setTimeout(function () {
        formatDate($('#startDate'));
    }, 1);
});

$('#endDate').blur(function () {
    setTimeout(function () {
        formatDate($('#endDate'));
    }, 1);
});